import pytest
from time import time
from lib.config import CONFIG
from lib.mysql_client import MySQLClient
from lib.http_client import HTTPClient
from lib.logger import Logger

base_url = CONFIG["api_test"]["base_url"]

@pytest.fixture        # 定义一个fixture
def f_register_and_delete():
    logger = Logger()
    logger.info("=== setup ===")
    http_client = HTTPClient()
    mysql_client = MySQLClient()
    # setup
    # 准备测试数据
    name = "test_" + str(time())
    password = "123456"

    # 准备接口的数据
    method = "POST"
    path = "/register/"
    data = {
        "name": name,
        "password1": password,
        "password2": password
    }

    # 调用接口
    r = http_client.request(method=method, path=path, json=data)
    http_client.update(
        {
            "token": r.json()["data"]["openid"],
            "operator": str(r.json()["data"]["user_id"])
        }
    )
    # 断言
    # 1. HTTP状态码断言
    expect_value = 200
    current_value = r.status_code
    assert current_value == expect_value, f"HTTP状态码应该为{expect_value},实际结果为{current_value}!!!"
    # 2. CODE的值的断言
    expect_value = "200"
    current_value = r.json()["code"]
    assert current_value == expect_value, f"code字段的值应该为\"{expect_value}\",实际结果为\"{current_value}\"!!!"
    yield name, password, http_client, mysql_client
    logger.info("=== teardown ===")
    # teardown
    # 连接数据库

    sqls = [
        f"DELETE FROM auth_user WHERE username=\"{name}\";",
        f"DELETE FROM user_profile WHERE name=\"{name}\";"
    ]
    mysql_client.execute(sqls)


@pytest.fixture
def create_asn(f_register_and_delete):
    name, password, http_client, mysql_client = f_register_and_delete
    data = {
        "path": "/asn/list/",
        "method": "POST",
        "json": {
            "creater": name
        }
    }
    r = http_client.request(**data)
    assert 1 == r.json()["asn_status"]
    asn_id = r.json()["id"]
    asn_code = r.json()["asn_code"]
    yield name, asn_id, asn_code, http_client, mysql_client
    sqls = [
        f"DELETE FROM asnlist WHERE asn_code=\"{asn_code}\" AND creater=\"{name}\";"
    ]
    mysql_client.execute(sqls)


